package dwei.hk
{
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.text.TextField;
	
	import mx.core.Application;

	/**
	 * 热键管理器
	 */	
	public class HKMgr
	{
//============================================================================
//INITALIZE
//============================================================================
		private static function init():void
		{
			var app:Application = Application.application as Application;
			if (app.initialized)
			{
				app.stage.addEventListener(KeyboardEvent.KEY_DOWN, appKeyDown_handler);
				app.stage.addEventListener(KeyboardEvent.KEY_UP, appKeyUp_handler);
			}
			else
			{
				app.addEventListener(Event.ADDED_TO_STAGE, addedToStage_handler);
			}
		}
		init();
//============================================================================
//PROPERTY
//============================================================================
		/**
		 * 当前热键接收器
		 */		
		public static var localHK:IHK;
		/**
		 * 全局热键接收器
		 */		
		public static var globalHK:IHK;
//============================================================================
//PUBLIC
//============================================================================
		public static function getKey(keyCode:uint, ctrl:Boolean = false, shift:Boolean = false, alt:Boolean = false):String
		{
			var keySet:Array = [ctrl, shift, alt, keyCode];
			return keySet.join(",");
		}
//============================================================================
//HANDLER
//============================================================================
		private static function addedToStage_handler(event:Event):void
		{
			var app:Application = Application.application as Application;
			app.removeEventListener(Event.ADDED_TO_STAGE, addedToStage_handler);
			
			app.stage.addEventListener(KeyboardEvent.KEY_DOWN, appKeyDown_handler);
			app.stage.addEventListener(KeyboardEvent.KEY_UP, appKeyUp_handler);
		}
		private static function appKeyDown_handler(event:KeyboardEvent):void
		{
			var app:Application = Application.application as Application;
			if (app.getFocus() is TextField) return;
			var key:String = getKey(event.keyCode, event.ctrlKey, event.shiftKey, event.altKey);
			if (localHK != null) localHK.keyDown(key);
			if (globalHK != null) globalHK.keyDown(key);
		}
		private static function appKeyUp_handler(event:KeyboardEvent):void
		{
			var app:Application = Application.application as Application;
			if (app.getFocus() is TextField) return;
			var key:String = getKey(event.keyCode, event.ctrlKey, event.shiftKey, event.altKey);
			if (localHK != null) localHK.keyUp(key);
			if (globalHK != null) globalHK.keyUp(key);
		}
	}
}